<template>
  <div class="job-management-page">
    <!-- 搜索栏区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.jobName"
        placeholder="请输入岗位名称"
        style="width: 200px; margin-right: 10px"
      />
      <el-input
        v-model="searchForm.jobCode"
        placeholder="请输入岗位编码"
        style="width: 200px; margin-right: 10px"
      />
      <el-select
        v-model="searchForm.jobType"
        placeholder="请选择岗位类别"
        style="width: 200px; margin-right: 10px"
      >
        <el-option
          v-for="item in jobTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="handleQuery" color="#203A64">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" color="#203A64" @click="openAddDialog"
        >新增岗位</el-button
      >
    </div>

    <!-- PC端表格 -->
    <el-table
      v-if="!isMobile"
      :data="tableData"
      border
      style="width: 100%; margin-top: 16px"
    >
      <el-table-column prop="jobName" label="岗位名称" />
      <el-table-column prop="jobCode" label="岗位编码" />
      <el-table-column prop="jobType" label="岗位类别" />
      <el-table-column prop="orgName" label="所属组织" />
      <el-table-column prop="employeeCount" label="员工人数" />
      <el-table-column prop="description" label="岗位描述" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button :link="true" size="small" @click="showEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            :link="true"
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 移动端卡片式列表 -->
    <div v-else>
      <div v-for="row in tableData" :key="row.jobCode + row.jobName" class="mobile-card">
        <div class="mobile-row">
          <span class="mobile-label">岗位名称：</span>
          <span>{{ row.jobName }}</span>
        </div>
        <div class="mobile-row">
          <span class="mobile-label">岗位编码：</span>
          <span>{{ row.jobCode }}</span>
        </div>
        <div class="mobile-row">
          <span class="mobile-label">岗位类别：</span>
          <span>{{ row.jobType }}</span>
        </div>
        <div class="mobile-row">
          <span class="mobile-label">所属组织：</span>
          <span>{{ row.orgName }}</span>
        </div>
        <div class="mobile-row">
          <span class="mobile-label">员工人数：</span>
          <span>{{ row.employeeCount }}</span>
        </div>
        <div class="mobile-row mobile-actions">
          <el-button size="small" @click="showDetail(row)">详情</el-button>
          <el-button size="small" @click="showEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row)"
            class="delete-button"
            >删除</el-button
          >
        </div>
      </div>
    </div>

    <!-- 分页区域 -->
    <div class="pagination" :class="{ 'mobile-pagination': isMobile }">
      <span v-if="!isMobile">共 {{ total }} 条</span>
      <el-pagination
        background
        layout="prev, pager, next, sizes"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :small="isMobile"
        :page-sizes="[5, 10, 15, 20]"
        :style="
          isMobile
            ? 'width: 100%; overflow-x: auto; font-size: 15px; padding: 4px 0;'
            : ''
        "
      />
    </div>

    <!-- 添加弹窗 -->
    <el-dialog v-model="addDialogVisible" title="添加岗位" width="500px" align-center>
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="岗位名称" prop="jobName" required>
          <el-input v-model="addForm.jobName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="岗位分类" prop="jobType" required>
          <el-select v-model="addForm.jobType" placeholder="请选择">
            <el-option
              v-for="item in jobTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工人数" prop="employeeCount" required>
          <el-input
            v-model="addForm.employeeCount"
            placeholder="请输入"
            type="number"
            min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleAddCancel">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm" color="#203A64"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑岗位" width="500px" align-center>
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="岗位名称" prop="jobName" required>
          <el-input v-model="editForm.jobName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="岗位分类" prop="jobType" required>
          <el-select v-model="editForm.jobType" placeholder="请选择">
            <el-option
              v-for="item in jobTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工人数" prop="employeeCount" required>
          <el-input
            v-model="editForm.employeeCount"
            placeholder="请输入"
            type="number"
            min="0"
          />
        </el-form-item>
        <el-form-item label="岗位描述" prop="description">
          <el-input
            v-model="editForm.description"
            placeholder="请输入"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleEditCancel">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm" color="#203A64"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 移动端详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="岗位详情"
      width="90vw"
      align-center
      :close-on-click-modal="true"
      :show-close="true"
      class="mobile-detail-dialog"
      v-if="isMobile"
    >
      <div v-if="detailData" class="mobile-detail-content">
        <div class="mobile-detail-row">
          <span class="mobile-label">岗位名称：</span>{{ detailData.jobName }}
        </div>
        <div class="mobile-detail-row">
          <span class="mobile-label">岗位编码：</span>{{ detailData.jobCode }}
        </div>
        <div class="mobile-detail-row">
          <span class="mobile-label">岗位类别：</span>{{ detailData.jobType }}
        </div>
        <div class="mobile-detail-row">
          <span class="mobile-label">所属组织：</span>{{ detailData.orgName }}
        </div>
        <div class="mobile-detail-row">
          <span class="mobile-label">员工人数：</span>{{ detailData.employeeCount }}
        </div>
        <div class="mobile-detail-row">
          <span class="mobile-label">岗位描述：</span>{{ detailData.description }}
        </div>
        <div class="mobile-detail-row">
          <span class="mobile-label">更新时间：</span>{{ detailData.updateTime }}
        </div>
      </div>
      <template #footer>
        <el-button
          type="primary"
          style="width: 100%; font-size: 16px"
          @click="detailDialogVisible = false"
          >关闭</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from "vue";
import type { FormInstance } from "element-plus";
import { getJobList, addJob, queryJobByName, deleteJob, updateJob } from "@/utils/api";
import { ElMessageBox, ElMessage } from "element-plus";

// 定义岗位数据结构
interface Job {
  id: string;
  jobName: string;
  jobCode: string;
  jobType: string;
  orgName: string;
  employeeCount: number;
  description: string;
  updateTime?: string;
}

// 搜索表单数据（双向绑定）
const searchForm = reactive({
  jobName: "", // 岗位名称
  jobCode: "", // 岗位编码
  jobType: "", // 岗位类别
});

// 岗位类别下拉选项
const jobTypeOptions = [
  { label: "技术岗", value: "技术岗" },
  { label: "营销岗", value: "营销岗" },
  { label: "财务岗", value: "财务岗" },
  { label: "人力岗", value: "人力岗" },
];

// 表格数据（当前页数据）
const tableData = ref<Job[]>([]);
// 分页参数
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页条数
const total = ref(0); // 总数据条数
const allData = ref<Job[]>([]); // 保存全部岗位数据

/** 加载数据（含分页+搜索逻辑，已对接后端） */
const loadData = async () => {
  const params = {
    jobName: searchForm.jobName,
    jobCode: searchForm.jobCode,
    jobType: searchForm.jobType,
    // page: currentPage.value, // 不传分页参数，前端分页
    // pageSize: pageSize.value,
  };
  try {
    const res = await getJobList(params);
    // 适配后端直接返回数组，前端分页
    allData.value = Array.isArray(res.data) ? res.data : [];
    total.value = allData.value.length;
    // 只展示当前页数据
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    tableData.value = allData.value.slice(start, end);
  } catch (e) {
    allData.value = [];
    tableData.value = [];
    total.value = 0;
  }
};

// 页面加载时初始化数据
onMounted(() => {
  loadData();
});

/** 点击"查询"按钮：重置页码后重新加载数据 */
const handleQuery = async () => {
  currentPage.value = 1; // 搜索后回到第 1 页
  await loadData();
};

/** 点击"重置"按钮：清空搜索条件 + 重置分页 + 重新加载数据 */
const handleReset = async () => {
  searchForm.jobName = "";
  searchForm.jobCode = "";
  searchForm.jobType = "";
  currentPage.value = 1;
  pageSize.value = 5;
  await loadData();
};

/** 分页-切换每页条数 */
const handleSizeChange = async (newSize: number) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  // 只需 slice allData
  const start = 0;
  const end = start + pageSize.value;
  tableData.value = allData.value.slice(start, end);
};

/** 分页-切换页码 */
const handlePageChange = async (newPage: number) => {
  currentPage.value = newPage;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  tableData.value = allData.value.slice(start, end);
};

// 移动端判断
const isMobile = ref(window.innerWidth < 1000);
const handleResize = () => {
  isMobile.value = window.innerWidth < 1000;
};
onMounted(() => window.addEventListener("resize", handleResize));
onUnmounted(() => window.removeEventListener("resize", handleResize));

// 移动端卡片操作方法（可根据需要完善弹窗等）
const detailDialogVisible = ref(false);
const detailData = ref<Job | null>(null);

function showDetail(row: Job) {
  detailData.value = row;
  detailDialogVisible.value = true;
}

const editDialogVisible = ref(false);
const editForm = ref({
  jobName: "",
  jobType: "",
  employeeCount: "",
  description: "",
});
const editFormRef = ref<FormInstance | null>(null);
const editRules = {
  jobName: [{ required: true, message: "请输入岗位名称", trigger: "blur" }],
  jobType: [{ required: true, message: "请选择岗位分类", trigger: "change" }],
  employeeCount: [{ required: true, message: "请输入员工人数", trigger: "blur" }],
};

const editId = ref<string | null>(null);

function showEdit(row: Job) {
  editDialogVisible.value = true;
  editId.value = row.id; // 记录当前编辑项id
  editForm.value = {
    jobName: row.jobName,
    jobType: row.jobType,
    employeeCount: String(row.employeeCount),
    description: row.description || "",
  };
}

function handleEditCancel() {
  editDialogVisible.value = false;
}

async function handleEditConfirm() {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid: boolean) => {
    if (valid && editId.value) {
      try {
        await updateJob(editId.value, {
          jobName: editForm.value.jobName,
          jobType: editForm.value.jobType,
          employeeCount: Number(editForm.value.employeeCount),
          description: editForm.value.description,
        });
        editDialogVisible.value = false;
        await loadData();
        ElMessage.success("编辑成功");
      } catch (e) {
        ElMessage.error("编辑失败");
      }
    }
  });
}

function handleDelete(row: Job) {
  ElMessageBox.confirm(`确定要删除岗位 " ${row.jobName} " 吗？`, "删除确认", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteJob(row.id);
        ElMessage.success("删除成功");
        await loadData();
      } catch (e) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
}

// 添加弹窗相关
const addDialogVisible = ref(false);
const addForm = ref({
  jobName: "",
  jobType: "",
  employeeCount: "",
});
const addFormRef = ref<FormInstance | null>(null);
const addRules = {
  jobName: [{ required: true, message: "请输入岗位名称", trigger: "blur" }],
  jobType: [{ required: true, message: "请选择岗位分类", trigger: "change" }],
  employeeCount: [{ required: true, message: "请输入员工人数", trigger: "blur" }],
};

function openAddDialog() {
  addDialogVisible.value = true;
  addForm.value = { jobName: "", jobType: "", employeeCount: "" };
}

async function handleAddConfirm() {
  if (!addFormRef.value) return;
  addFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 只提交弹窗中填写的内容，未填写的字段不传
        const payload: any = {};
        if (addForm.value.jobName) payload.jobName = addForm.value.jobName;
        if (addForm.value.jobType) payload.jobType = addForm.value.jobType;
        if (addForm.value.employeeCount)
          payload.employeeCount = Number(addForm.value.employeeCount);
        await addJob(payload);
        addDialogVisible.value = false;
        await loadData();
        ElMessage.success("新增成功");
      } catch (e) {
        ElMessage.error("新增失败");
      }
    }
  });
}
function handleAddCancel() {
  addDialogVisible.value = false;
}
</script>

<style scoped>
.job-management-page {
  padding: 20px;
  background-color: #fff;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

/* 操作按钮栏样式 */
.action-buttons {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
}
.el-button[type="primary"] {
  background: #203a64;
  border-color: #203a64;
  color: #fff;
}
.el-button[type="primary"]:hover {
  background: #35507c;
  border-color: #35507c;
}

/* 表格操作列按钮 */
:deep(.el-table .el-button) {
  color: #203a64;
  font-weight: 500;
}
:deep(.el-table .el-button[type="danger"]) {
  color: #f56c6c;
}

/* 分页栏样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 16px;
}
.pagination span {
  margin-right: 10px;
}
:deep(.el-pagination .el-pager li) {
  color: #203a64;
}
:deep(.el-pagination .el-pager li.is-active) {
  background: #203a64 !important;
  color: #fff !important;
  border-radius: 4px;
}
:deep(.el-select-dropdown__item) {
  color: #203a64;
}
:deep(.el-select-dropdown__item.selected) {
  background: #203a64 !important;
  color: #fff !important;
}

/* 移动端适配 */
@media (max-width: 1000px) {
  .job-management-page {
    padding: 8px;
  }
  .search-bar,
  .action-buttons {
    margin-bottom: 8px;
  }
  .search-bar .el-input,
  .search-bar .el-select {
    width: 110px !important;
    font-size: 13px;
  }
  .el-table {
    font-size: 12px !important;
  }
  .el-table th,
  .el-table td {
    padding: 4px 6px !important;
  }
  .el-button {
    margin-right: 4px !important;
    font-size: 13px !important;
    padding: 4px 8px !important;
  }
  .el-table td .el-table__cell {
    display: flex !important;
    flex-direction: row !important;
    align-items: center;
    gap: 4px;
    white-space: nowrap !important;
  }
  .el-table td .el-button {
    margin-right: 0 !important;
  }
  .pagination {
    margin-top: 8px;
  }
}

/* 复用组织架构页的移动端卡片样式 */
.mobile-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 12px;
  padding: 12px 16px;
}
.mobile-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.mobile-label {
  color: #888;
  min-width: 80px;
  font-size: 14px;
}
.mobile-actions {
  margin-top: 8px;
  gap: 8px;
}
.mobile-actions .el-button {
  margin-right: 8px;
}
.mobile-actions .delete-button > span {
  color: #fff;
  background-color: #f56c6c;
}
/* 移动端分页适配 */
.mobile-pagination {
  overflow-x: auto;
  padding-bottom: 4px;
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
.el-form-item__label {
  font-weight: 500;
}
.el-form-item.is-required .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

@media (max-width: 1000px) {
  .el-dialog {
    width: 95vw !important;
    min-width: unset !important;
    max-width: 100vw !important;
  }
  .el-dialog :deep(.el-form-item__label) {
    font-size: 14px;
  }
  .el-dialog :deep(.el-input),
  .el-dialog :deep(.el-select) {
    font-size: 14px;
  }
  .el-dialog :deep(.el-button) {
    font-size: 14px;
    padding: 8px 16px;
  }
  .dialog-footer {
    padding: 0 20px 20px;
  }
}

.mobile-detail-dialog >>> .el-dialog__body {
  padding: 12px 8px;
}
.mobile-detail-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-detail-row {
  display: flex;
  align-items: flex-start;
  font-size: 15px;
  word-break: break-all;
}
.mobile-detail-row .mobile-label {
  min-width: 90px;
  color: #888;
  font-weight: 500;
}
</style>
